package com.example.system.Service.sysuser.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.core.domain.R;
import com.example.common.core.domain.ResultCode;
import com.example.system.Service.sysuser.ISysUserService;
import com.example.system.domain.sysuser.SysUser;
import com.example.system.domain.sysuser.dto.LoginDTO;
import com.example.system.domain.vo.LogionUserVo;
import com.example.system.mapper.SysUserMapper;
import com.example.system.utils.BCryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SysUserService implements ISysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    public int insertUser(SysUser sysUser) {
        return sysUserMapper.insert(sysUser);
    }

    /**
     * 1.校验一下账号在数据库中是否存在
     * 2.
     *
     * @param userAccount
     * @param password
     * @return
     */
    @Override
    public R<String> login(String userAccount, String password) {
        //通过账号去数据库中查询，对应的用户信息
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        //select password from tb_sys_user where user_account = #{userAccount}
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper
                .select(SysUser::getUserId, SysUser::getAccount, SysUser::getPassword)
                .eq(SysUser::getAccount, userAccount));

        if (sysUser == null) {
            return R.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        if (BCryptUtils.matchesPassword(password, sysUser.getPassword())) {
            return R.ok("1111111111111111111111", ResultCode.SUCCESS);
        }
        return R.fail(ResultCode.FAILED_LOGIN);
    }

    @Override
    public R<String> login(LoginDTO loginDTO) {
        return login(loginDTO.getUserAccount(), loginDTO.getPassword());
    }

    @Override
    public R<LogionUserVo> info(String tokens) {
        return null;
    }
}
